package net.sf.l2j.gameserver.handler.voicedcommandhandlers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.l2j.Config;
import net.sf.l2j.database.L2DatabaseFactory;
import net.sf.l2j.gameserver.cache.HtmCache;
import net.sf.l2j.gameserver.handler.IVoicedCommandHandler;
import net.sf.l2j.gameserver.model.L2World;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.network.SystemMessageId;
import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
import net.sf.l2j.gameserver.templates.StatsSet;
import net.sf.l2j.util.PcAction;

public class menu implements IVoicedCommandHandler 
{

	private static final String[] VOICED_COMMANDS = { "menu", "eon_menu_" };
	String str = "";
	private long time;

	@Override
	public boolean useVoicedCommand(String command, L2PcInstance activeChar,String target) 
	{

		if (command.equalsIgnoreCase("menu"))
		{
			showHtm(activeChar);
		} 
		else if (command.startsWith("eon_menu_"))
		{
			String addcmd = command.substring(9).trim();
			if (addcmd.startsWith("exp")) 
			{
				int flag = Integer.parseInt(addcmd.substring(3).trim());
				if (flag == 0) 
				{
					activeChar.setExpOn(false);
					activeChar.sendMessage("- Получение опыта отключено. Помни! Для отмытия кармы нужен опыт!");
				} 
				else 
				{
					activeChar.setExpOn(true);
					activeChar.sendMessage("- Получение опыта возобновлено");
				}
				showHtm(activeChar);
				return true;
			}
			if (addcmd.startsWith("loot")) 
			{
				int flag = Integer.parseInt(addcmd.substring(4).trim());
				if (flag == 0) 
				{
					activeChar.setAutoLoot(false);
					activeChar.sendMessage("- Автолут отключен!");
				} 
				else 
				{
					activeChar.setAutoLoot(true);
					activeChar.sendMessage("- Автолут включен!");
				}
				showHtm(activeChar);
				return true;
			}

			if (addcmd.startsWith("offline")) 
			{
				if ((Config.OFFLINE_TRADE_ENABLE && (activeChar.getPrivateStoreType() == 1
						|| activeChar.getPrivateStoreType() == 3 || activeChar.getPrivateStoreType() == 8))
						|| (Config.OFFLINE_CRAFT_ENABLE && activeChar.getPrivateStoreType() == 5))
				{
					activeChar.store();
					activeChar.closeNetConnection();
				} 
				else 
				{
					activeChar.sendMessage("- Вы не можете использовать оффлайн торговлю/крафт в данный момент");
					showHtm(activeChar);
				}
				return true;
			}

			if (addcmd.startsWith("trade")) 
			{
				int flag = Integer.parseInt(addcmd.substring(5).trim());
				if (flag == 0)
				{
					activeChar.setTradeRefusal(false);
					activeChar.sendMessage("- Возможность использовать трейд включена");
				} 
				else 
				{
					activeChar.setTradeRefusal(true);
					activeChar.sendMessage("- Возможность использовать трейд отключена");
				}
				showHtm(activeChar);
				return true;
			}

			if (addcmd.startsWith("pm")) 
			{
				int flag = Integer.parseInt(addcmd.substring(2).trim());
				if (flag == 0) 
				{
					activeChar.setMessageRefusal(false);
					activeChar.sendPacket(new SystemMessage(SystemMessageId.MESSAGE_ACCEPTANCE_MODE));
				} 
				else
				{
					activeChar.setMessageRefusal(true);
					activeChar.sendPacket(new SystemMessage(SystemMessageId.MESSAGE_REFUSAL_MODE));
				}
				showHtm(activeChar);
				return true;
			}

			if (addcmd.startsWith("prem"))
			{
				int flag = Integer.parseInt(addcmd.substring(4).trim());
				if (flag == 0) 
				{
					showPremHtm(activeChar);
				} 
				else if (flag == 1)
				{
					if (activeChar.getInventory().getItemByItemId(Config.Service_Premium1_Item_Id) == null || activeChar.getInventory().getItemByItemId(Config.Service_Premium1_Item_Id).getCount() < Config.Service_Premium1_Item_Count)
					{
						activeChar.sendMessage("- Не хватает монет");
						showPremHtm(activeChar);
						return false;
					}
					
					showPremHtm(activeChar);
					try 
					{
						if (Config.USE_PREMIUMSERVICE)
						{
							PcAction.addPremiumServices(1, activeChar.getAccountName());
							activeChar.destroyItemByItemId("Consume",Config.Service_Premium1_Item_Id,Config.Service_Premium1_Item_Count, activeChar,false);
							activeChar.sendMessage("- Вы получили премиум аккаунт на 1 месяц. Новое получение не добавляет время, а обновляет!");
						}
						else
						{
							activeChar.sendMessage("- Сервис отключен администратором");
						}
					} 
					catch (StringIndexOutOfBoundsException e) 
					{
						activeChar.sendMessage("- Ошибка");
					}
					activeChar.store();
				} 
				else if (flag == 2) 
				{
					showHtm(activeChar);
				}
				return true;
			}
		}
		return true;
	}

	private void showHtm(L2PcInstance activeChar) 
	{
		NpcHtmlMessage htm = new NpcHtmlMessage(activeChar.getLastQuestNpcObject());
		String text = HtmCache.getInstance().getHtm("data/html/mods/menu/menu.htm");
		htm.setHtml(text);
		activeChar.sendPacket(htm);
		L2World.getInstance();
		int realonl = L2World.getAllPlayersCount();
		htm.replace("%online%", realonl);
		if (activeChar.getExpOn()) 
		{
			htm.replace("%gainexp%", "ON");
		} 
		else 
		{
			htm.replace("%gainexp%", "OFF");
		}
		if (activeChar.isAutoLoot()) 
		{
			htm.replace("%autoloot%", "ON");
		} 
		else 
		{
			htm.replace("%autoloot%", "OFF");
		}
		if (activeChar.getTradeRefusal()) 
		{
			htm.replace("%trade%", "OFF");
		} 
		else 
		{
			htm.replace("%trade%", "ON");
		}
		if (activeChar.getMessageRefusal()) 
		{
			htm.replace("%pm%", "OFF");
		}
		else
		{
			htm.replace("%pm%", "ON");
		}
	}

	protected StatsSet _StateSet;

	private void showPremHtm(L2PcInstance activeChar) 
	{
		NpcHtmlMessage htm = new NpcHtmlMessage(activeChar.getLastQuestNpcObject());
		String text = HtmCache.getInstance().getHtm("data/html/mods/menu/menu-pa.htm");
		htm.setHtml(text);
		activeChar.sendPacket(htm);
		htm.replace("%price1%", str + Config.Service_Premium1_Item_Count);
		if (activeChar.getPremiumService() == 0)
			htm.replace("%exptime%", "не активирован");
		else if (activeChar.getPremiumService() == 1) 
		{
			getExpTime(activeChar.getName());
			String date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date(time));
			htm.replace("%exptime%", date);
		}
	}

	private void getExpTime(String accName) 
	{
		Connection con = null;
		try 
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT enddate FROM character_premium WHERE account_name=?");
			statement.setString(1, accName);
			ResultSet rset = statement.executeQuery();
			while (rset.next()) 
			{
				time = rset.getLong("enddate");
			}
			rset.close();
			statement.close();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		} 
		finally 
		{
			try 
			{
				con.close();
			} 
			catch (Exception e) 
			{
			}
		}
	}

	@Override
	public String[] getVoicedCommandList() 
	{
		return VOICED_COMMANDS;
	}
}